package pong.views
{
	import flash.display.DisplayObject;
	import flash.display.DisplayObjectContainer;
	import flash.display.MovieClip;
	import flash.events.Event;
	
	import loader.ILoaderModel;
	import loader.ILoaderView;
	
	public class PongLoaderView implements ILoaderView
	{
		
		private var _model:ILoaderModel;
		
		private var _skin:DisplayObjectContainer;
		
		private var _container:DisplayObjectContainer;
		
		
		public function PongLoaderView(model:ILoaderModel, skin:DisplayObjectContainer, container:DisplayObjectContainer) 
		{
			this._model = model;
			
			this._skin = skin;
			
			this._container = container;
			
			this.update();
			
			this.addEvents();
		}
		
		
		private function addEvents():void
		{
			this._model.addEventListener(Event.CHANGE, this.onModelChange);
		}
		
		
		private function removeEvents():void
		{
			this._model.removeEventListener(Event.CHANGE, this.onModelChange);
		}
		
		
		private function onModelChange(e:Event):void
		{
			this.update();
		}
		
		
		private function update():void
		{
			if (this._model.isShowing)
			{
				// update progress
				this.setProgress(this._model.progress);
				
				// update visibility
				if (!this._container.contains(this._skin))
					this._container.addChild(this._skin);
			}
			else
			{
				// update visibility
				if (this._container.contains(this._skin))
					this._container.removeChild(this._skin);
			}
		}
		
		
		
		private function setProgress(progress:Number):void
		{
			// TODO: read skin locations from config
			var progressSkin:MovieClip = this._skin.getChildByName("diskProgress") as MovieClip;			

			var frame:int = (progress * progressSkin.totalFrames) + 1;
			
			progressSkin.gotoAndStop(frame);
		}
		
		
		
		public function dispose():void 
		{
			this.removeEvents();
			
			if (this._container.contains(this._skin))
				this._container.removeChild(this._skin);
		}
		
		
	}
}